# coding utf-8
from Software_Set_UI import Ui_MainWindow
from PyQt5.QtWidgets import QApplication, QWidget, QHBoxLayout, QVBoxLayout, QToolButton, QSizePolicy, QPushButton, \
    QGroupBox, QGridLayout
from PyQt5.QtGui import QIcon, QFont, QPixmap
from PyQt5.QtCore import QPoint, QRect, QSize, Qt  # , pyqtSignal
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5 import QtWidgets, QtCore
from PyQt5 import QtGui
# PySide2
# PyQt5
import sys
import os
from os import environ, listdir, makedirs, pathsep, startfile
# from PyQt5 import QtCore, QtGui, QtWidgets
import json

import xml.dom.minidom

so = []
class mainWindow(Ui_MainWindow, QMainWindow):
    def __init__(self):
        super(mainWindow, self).__init__()
        self.setupUi(self)
        self.Project_WidgetItem_import()

        self.Button_Clicked()

        self.line_edit_list = []
    def Project_WidgetItem_import(self):
        ProjecinfoPath = 'H:\QL_tool_file\Window_Tool\Logical File\SoftwareStarter\Projecinfo'
        for i in os.listdir(ProjecinfoPath):  # 循环读取路径下的文件并筛选输出
            if os.path.splitext(i)[1] == ".json":  # json
                # print(i.split('.')[0])
                with open(ProjecinfoPath + '/' + i, 'r', encoding='utf8') as fp:
                    json_data = json.load(fp)  # 读取json文件
                    # print(json_data["Project_en"])
                    if i.split('.')[0] == json_data["Project_en"]:
                        new_item = QListWidgetItem(json_data["Project_en"])
                        new_item.setSizeHint(QtCore.QSize(180, 50))  # 设置按钮的高度为40
                        font = new_item.font()
                        font.setPointSize(14)  # 设置字体大小为14
                        new_item.setFont(font)
                        self.Project_Set_listWidget.addItem(new_item)
        self.Project_Set_listWidget.itemSelectionChanged.connect(lambda *args: self.on_selection_changed(json_data))
    ##选择项目
    def on_selection_changed(self, json_data):
        selected_items = self.Project_Set_listWidget.selectedItems()
        for item in selected_items:
            print(item.text())
            if json_data["Project_en"] == item.text():
                self.Project_en_lineEdit.setText(json_data["Project_en"])
                self.Project_cn_lineEdit.setText(json_data["Project_cn"])
                self.Start_Time_lineEdit.setText(json_data["Start_Time"])
                self.Frame_lineEdit.setText(json_data["Frame"])
                self.ImageHeight_lineEdit.setText(json_data["ImageHeight"])
                self.ImageWidth_lineEdit.setText(json_data["ImageWidth"])
                self.ImageScale_lineEdit.setText(json_data["ImageScale"])
                self.Project_local_Path_lineEdit.setText(json_data["Project_local_Path"])
                self.Project_Network_Path_lineEdit.setText(json_data["Project_Network_Path"])
                self.Project_assets_Path_lineEdit.setText(json_data["Project_assets_Path"])
                Modile_set = json_data["Modile_set"]
                for Modile in range(len(Modile_set)):
                    self.__New_Modile_lineEdit()
                    self.NewModile_line_edit.setText(Modile_set[Modile]["ModileName"])


                Shot_set = json_data["Shot_set"]
                self.Set_lineEdit.setText(Shot_set["Set"])
                self.Set_Split_lineEdit.setText(Shot_set["Set_Split"])
                self.Events_lineEdit.setText(Shot_set["Events"])
                self.Events_Split_lineEdit.setText(Shot_set["Events_Split"])
                self.Lens_lineEdit.setText(Shot_set["Lens"])
                self.Lens_Split_lineEdit.setText(Shot_set["Lens_Split"])
                self.Class_lineEdit.setText(Shot_set["Class"])
                self.Class_Split_lineEdit.setText(Shot_set["Class_Split"])
                self.Version_lineEdit.setText(Shot_set["Version"])
                self.VersionNumber_lineEdit.setText(Shot_set["VersionNumber"])
                self.FileFormat_lineEdit.setText(Shot_set["FileFormat"])

                Variable_set = json_data["Variable_set"]
                for Variable in Variable_set:
                    #print(Variable)
                    if not Variable:
                        self.__New_Variable_lineEdit(None, None)
                    else:
                        self.__New_Variable_lineEdit(Variable["Name"],Variable["Value"])

        self.New_Software_Button.clicked.connect(lambda *args: self.New_Software())

    ##创建新的启动器
    def New_Software(self):
        text, ok = QInputDialog.getText(self, "启动器名称", "请输入新启动器名称:")
        if ok:


            self.NewLauncher_Layout = QtWidgets.QVBoxLayout()
            self.NewLauncher_Layout.setObjectName(text + "_NewLauncher_Layout")
            self.Software_horizontal_Layout = QtWidgets.QHBoxLayout()
            self.Software_horizontal_Layout.setObjectName("Software_horizontal_Layout")
            self.Software_Name_Button = QtWidgets.QPushButton(text)
            self.Software_Name_Button.setMinimumSize(QtCore.QSize(0, 30))
            self.Software_Name_Button.setObjectName(text)
            self.Software_horizontal_Layout.addWidget(self.Software_Name_Button)
            self.New_Variable_Button = QtWidgets.QPushButton(self.starter_settings_widget)
            self.New_Variable_Button.setMinimumSize(QtCore.QSize(30, 30))
            self.New_Variable_Button.setMaximumSize(QtCore.QSize(30, 30))
            self.New_Variable_Button.setObjectName(text + "_New_Variable_Button")
            self.Software_horizontal_Layout.addWidget(self.New_Variable_Button)
            self.Software_Del_Button = QtWidgets.QPushButton(self.starter_settings_widget)
            self.Software_Del_Button.setMinimumSize(QtCore.QSize(30, 30))
            self.Software_Del_Button.setMaximumSize(QtCore.QSize(30, 30))
            self.Software_Del_Button.setObjectName(text + "_Software_Del_Button")
            self.Software_horizontal_Layout.addWidget(self.Software_Del_Button)
            self.Software_horizontal_Layout.setStretch(0, 1)
            self.NewLauncher_Layout.addLayout(self.Software_horizontal_Layout)
            self.Set_Software_Variable = QtWidgets.QVBoxLayout()
            self.Set_Software_Variable.setObjectName(text + "_Set_Software_Variable_Layout")
            self.Software_Path_Layout = QtWidgets.QHBoxLayout()
            self.Software_Path_Layout.setObjectName("Software_Path_Layout")
            self.Software_Path_LineEdit = QtWidgets.QLineEdit(self.starter_settings_widget)
            self.Software_Path_LineEdit.setObjectName(text + "_Software_Path_LineEdit")
            self.Software_Path_Layout.addWidget(self.Software_Path_LineEdit)
            self.Software_Path_Button = QtWidgets.QPushButton(self.starter_settings_widget)
            self.Software_Path_Button.setObjectName("Software_Path_Button")
            self.Software_Path_Layout.addWidget(self.Software_Path_Button)
            self.Set_Software_Variable.addLayout(self.Software_Path_Layout)

            self.Variable_List_groupBox = QtWidgets.QGroupBox(self.starter_settings_widget)
            self.Variable_List_groupBox.setMinimumSize(QtCore.QSize(0, 0))
            self.Variable_List_groupBox.setObjectName(text + "_Variable_List_groupBox")
            self.verticalLayout = QtWidgets.QVBoxLayout(self.Variable_List_groupBox)
            self.verticalLayout.setObjectName(text + "_Variable_List")

            

            self.Set_Software_Variable.addWidget(self.Variable_List_groupBox)
            self.NewLauncher_Layout.addLayout(self.Set_Software_Variable)
            self.starter_settings.addLayout(self.NewLauncher_Layout)
        self.New_Variable_Button.clicked.connect(lambda *args: self.New_Variable())
        self.Software_Del_Button.clicked.connect(lambda *args: self.Software_Del())

    # 递归删除布局函数
    def delete_Launcher_layout(self,layout):
        print(layout.objectName())
        while layout.count():
            item = layout.takeAt(0)
            widget = item.widget()
            sublayout = item.layout()
            if widget is not None:
                widget.deleteLater()
            elif sublayout is not None:
                self.delete_Launcher_layout(sublayout)
        parent = layout.parentWidget()
        if parent is not None:
            parent.layout().removeItem(layout)
        del layout

    def Software_Del(self):
        sender = self.sender()
        layouts = self.starter_settings.findChildren(QtWidgets.QVBoxLayout)
        #遍历 layouts 列表
        for layout in layouts:
            clickedList = sender.objectName().split("_")[0]
            if clickedList in layout.objectName() and "NewLauncher_Layout" in layout.objectName():
                self.delete_Launcher_layout(layout)


    #创建新的启动器环境变量
    def New_Variable(self):
        sender = self.sender()
        layouts = self.starter_settings_widget.findChildren(QtWidgets.QVBoxLayout)
        #遍历 layouts 列表
        for layout in layouts:
            clickedList = sender.objectName().split("_")[0]
            print(layout.objectName())

            if clickedList in layout.objectName() and clickedList + "_Set_Software_Variable_Layout" == layout.objectName():
                

                self.Variable_horizontal_Layout = QtWidgets.QHBoxLayout()
                self.Variable_horizontal_Layout.setSizeConstraint(QtWidgets.QLayout.SizeConstraint.SetMinAndMaxSize)
                self.Variable_horizontal_Layout.setObjectName("Variable_horizontal_Layout")
                self.Variable_lineEdit = QtWidgets.QLineEdit(self.Variable_List_groupBox)
                self.Variable_lineEdit.setObjectName("Variable_lineEdit")
                self.Variable_horizontal_Layout.addWidget(self.Variable_lineEdit)
                self.Value_lineEdit = QtWidgets.QLineEdit(self.Variable_List_groupBox)
                self.Value_lineEdit.setObjectName("Value_lineEdit")
                self.Variable_horizontal_Layout.addWidget(self.Value_lineEdit)
                self.Del_Variable_Button = QtWidgets.QPushButton(self.Variable_List_groupBox)
                self.Del_Variable_Button.setMinimumSize(QtCore.QSize(25, 25))
                self.Del_Variable_Button.setMaximumSize(QtCore.QSize(25, 25))
                self.Del_Variable_Button.setObjectName("Del_Variable_Button")
                self.Variable_horizontal_Layout.addWidget(self.Del_Variable_Button)
                layout.addLayout(self.Variable_horizontal_Layout)



    ###删除网格布局内的横向布局
    def delete_layout(self):
        sender = self.sender()
        print(sender.objectName())
        #child_widgets = self.Launcher_Set_widget.findChildren(QWidget)
        #for widget in child_widgets:
        #    for ValueQHBoxLayout in widget.findChildren(QtWidgets.QHBoxLayout):
        #        print(ValueQHBoxLayout.objectName())
#
        #        if sender.objectName() in ValueQHBoxLayout.objectName():
        #            ValueQHBoxLayout.setParent(None)
        #            ValueQHBoxLayout.deleteLater()
#


        '''
        for layout in self.gridLayout.findChildren(QHBoxLayout):
            if layout.objectName() == BoxLayoutCount:
                for inset in range(layout.count()):
                    item = layout.takeAt(0)
                    print(item)
                    widget = item.widget()
                    print(widget)
                    if widget:
                        widget.deleteLater()'''

    def show_context_menu(self, pos):
        sender = self.sender()  # 获取发送信号的对象
        menu = QMenu(sender)
        delete_action = QAction("删除", self)
        delete_action.triggered.connect(lambda: self.delete_line_edit(sender))
        menu.addAction(delete_action)
        menu.exec_(sender.mapToGlobal(pos))

    def delete_line_edit(self, line_edit):
        if line_edit in self.line_edit_list:
            line_edit.deleteLater()
            self.line_edit_list.remove(line_edit)
    ##按钮激活
    def Button_Clicked(self):
        ###设置按钮
        self.Project_Set_Bar.clicked.connect(self.__Project_Set_Visible)
        self.Project_Modile_Bar.clicked.connect(self.__Project_Modile_Visible)
        self.Shot_Set_Bar.clicked.connect(self.__Shot_Set_Visible)
        self.Launcher_Settings_Bar.clicked.connect(self.__Launcher_Settings_Visible)
        self.Project_Save.clicked.connect(self.__Project_Save_File)
        ###新建--删除
        self.Project_New.clicked.connect(self.__Project_New)
        self.Project_Del.clicked.connect(self.__Project_Del)

        self.NewModile_Button.clicked.connect(self.__New_Modile_lineEdit)





    def __Project_New(self):
        text, ok = QInputDialog.getText(self, "新建项", "请输入新项的名称:")
        if ok:
            new_item = QListWidgetItem(text)
            new_item.setSizeHint(QtCore.QSize(180, 50))  # 设置按钮的高度为40
            font = new_item.font()
            font.setPointSize(14)  # 设置字体大小为14
            new_item.setFont(font)
            self.Project_en_lineEdit.setText(text)
            self.Project_Set_listWidget.addItem(new_item)

    def __Project_Del(self):
        selectedItems = self.Project_Set_listWidget.selectedItems()
        for item in selectedItems:
            row = self.Project_Set_listWidget.row(item)
            self.Project_Set_listWidget.takeItem(row)

    ##创建新的项目模块
    def __New_Modile_lineEdit(self):
        self.NewModile_HBLayout = QtWidgets.QHBoxLayout()
        self.NewModile_HBLayout.setObjectName("NewModile_HBLayout")
        self.NewModile_line_edit = QtWidgets.QLineEdit(self.Project_Modile_info_widget)
        self.NewModile_line_edit.setObjectName("NewModile_line_edit")
        self.NewModile_HBLayout.addWidget(self.NewModile_line_edit)
        self.Del_modile_Button = QtWidgets.QPushButton(self.Project_Modile_info_widget)
        self.Del_modile_Button.setMinimumSize(QtCore.QSize(20, 20))
        self.Del_modile_Button.setMaximumSize(QtCore.QSize(20, 20))
        self.Del_modile_Button.setObjectName("Del_modile_Button")
        self.NewModile_HBLayout.addWidget(self.Del_modile_Button)

        row = self.Project_Modile_info_gridLayout.rowCount()  # 获取当前行数
        #print(row)
        column = 1  # 新的LineEdit总是放在第一列
        self.Project_Modile_info_gridLayout.addLayout(self.NewModile_HBLayout, row, column)  # 将LineEdit添加到下一行的第一列


    def __New_Variable_lineEdit(self,Variable,Value):
        BoxLayoutCount = 0
        column = 1  # 新的LineEdit总是放在第一列
        row = self.Launcher_info_gridLayout.rowCount()  # 获取当前行数
        for lenrow in range(row):
            BoxLayoutCount = BoxLayoutCount + 1
            self.horizontalLayout = QtWidgets.QHBoxLayout()
            self.horizontalLayout.setObjectName(str(BoxLayoutCount))
            self.Variable_lineEdit = QtWidgets.QLineEdit()
            self.Variable_lineEdit.setMinimumSize(QtCore.QSize(150, 0))
            self.Variable_lineEdit.setMaximumSize(QtCore.QSize(250, 16777215))
            self.Variable_lineEdit.setObjectName("Variable_lineEdit")
            self.horizontalLayout.addWidget(self.Variable_lineEdit)
            self.Value_lineEdit = QtWidgets.QLineEdit()
            self.Value_lineEdit.setMinimumSize(QtCore.QSize(0, 0))
            self.Value_lineEdit.setObjectName("Value_lineEdit")
            self.horizontalLayout.addWidget(self.Value_lineEdit)
            self.toolButton = QtWidgets.QPushButton(str(BoxLayoutCount))
            self.toolButton.setMinimumSize(QtCore.QSize(20, 20))
            self.toolButton.setMaximumSize(QtCore.QSize(50, 50))
            # self.toolButton.setObjectName(Variable)
            # self.toolButton.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)  # 使用customContextMenuRequested 必须要设置这行代码
            self.toolButton.clicked.connect(lambda *args: self.delete_layout(str(BoxLayoutCount)))
            self.horizontalLayout.addWidget(self.toolButton)

            #print(self.horizontalLayout.objectName())
            self.Variable_lineEdit.setText(Variable)
            self.Value_lineEdit.setText(Value)
        self.Launcher_info_gridLayout.addLayout(self.horizontalLayout, row, column)  # 将LineEdit添加到下一行的第一列





    def __Project_Set_Visible(self):
        # 切换内容区域的可见性
        self.Project_info_widget.setVisible(not self.Project_info_widget.isVisible())

    def __Project_Modile_Visible(self):
        # 切换内容区域的可见性
        self.Project_Modile_info_widget.setVisible(not self.Project_Modile_info_widget.isVisible())

    def __Shot_Set_Visible(self):
        # 切换内容区域的可见性
        self.ShotFile_info_widget.setVisible(not self.ShotFile_info_widget.isVisible())

    def __Launcher_Settings_Visible(self):
        # 切换内容区域的可见性
        if not None:
            pass
        else:
            self.Launcher_info_widget.setVisible(not self.Launcher_info_widget.isVisible())

    def __Project_Save_File(self):
        if len(self.Project_en_lineEdit.text()) <= 0:
            # 创建消息框对象
            msg_box = QMessageBox()
            # 设置消息框的标题和文本内容
            msg_box.setWindowTitle("提示")
            msg_box.setText("需填写项目中文名！")
            msg_box.exec_()
        else:
            Project_info = {}
            Project_info["Project_en"] = self.Project_en_lineEdit.text()
            Project_info["Project_cn"] = self.Project_cn_lineEdit.text()
            Project_info["Start_Time"] = self.Start_Time_lineEdit.text()
            Project_info["Frame"] = self.Frame_lineEdit.text()
            Project_info["ImageHeight"] = self.ImageHeight_lineEdit.text()
            Project_info["ImageWidth"] = self.ImageWidth_lineEdit.text()
            Project_info["ImageScale"] = self.ImageScale_lineEdit.text()
            Project_info["Project_local_Path"] = self.Project_local_Path_lineEdit.text()
            Project_info["Project_Network_Path"] = self.Project_Network_Path_lineEdit.text()
            Project_info["Project_assets_Path"] = self.Project_assets_Path_lineEdit.text()

            Project_ModileList = []
            line_edits = self.Project_Modile_info_widget.findChildren(QtWidgets.QLineEdit)
            for line_edit in line_edits:
                # 处理每一个lineEdit
                # print(line_edit.text())
                Project_Modile = {}
                Project_Modile["ModileName"] = line_edit.text()
                Project_ModileList.append(Project_Modile)
            Project_info["Modile_set"] = Project_ModileList

            # line_edits = self.Shot_Set_widget.findChildren(QtWidgets.QLineEdit)
            # for line_edit in line_edits:
            #    # 处理每一个lineEdit
            #    # print(line_edit.text())

            Project_ShotList = []
            Project_Shot = {}
            Project_Shot["Set"] = self.Set_lineEdit.text()
            Project_Shot["Set_Split"] = self.Set_Split_lineEdit.text()
            Project_Shot["Events"] = self.Events_lineEdit.text()
            Project_Shot["Events_Split"] = self.Events_Split_lineEdit.text()
            Project_Shot["Lens"] = self.Lens_lineEdit.text()
            Project_Shot["Lens_Split"] = self.Lens_Split_lineEdit.text()
            Project_Shot["Class"] = self.Class_lineEdit.text()
            Project_Shot["Class_Split"] = self.Class_Split_lineEdit.text()
            Project_Shot["Version"] = self.Version_lineEdit.text()
            Project_Shot["VersionNumber"] = self.VersionNumber_lineEdit.text()
            Project_Shot["FileFormat"] = self.FileFormat_lineEdit.text()
            # Project_ShotList.append(Project_Shot)
            Project_info["Shot_set"] = Project_Shot
            '''
            Launcher_Settings_List = []
            line_edits = self.Launcher_Settings_widget.findChildren(QtWidgets.QLineEdit)
            for line_edit in line_edits:
                # 处理每一个lineEdit
                #print(line_edit.text())
                Launcher_Settings = {}
                Launcher_Settings["Variable"] = line_edit.text()
                Launcher_Settings_List.append(Launcher_Settings)
            Project_info["Variable_set"] = Launcher_Settings_List
    '''
            #print(so)
            #Software = {}
            #variable = []
            #for i in so:
            #    for child  in self.Launcher_Set_widget.findChildren(QWidget):
            #            #print(child.objectName())
            #            if i == child.objectName():
            #                Software["Software"] = child.objectName()
            #                for layout in child.findChildren(QtWidgets.QHBoxLayout):
            #                    print(layout.objectName())
            SoftwareList = {}
            Software = {}
            VariableZip = {}
            VariableList=[]
            Variable = {}            
            NewLauncher_QVBoxLayout = self.starter_settings_widget.findChildren(QtWidgets.QVBoxLayout)
            for NewLauncher in NewLauncher_QVBoxLayout:
                for NewWidget in NewLauncher.findChildren(QtWidgets.QHBoxLayout):
                    for i in range(NewWidget.count()):
                        widget = NewWidget.itemAt(i).widget()
                        if isinstance(widget, QPushButton):
                            if widget.text() == widget.objectName():
                                Software["Software_Name"] = widget.text()
                            if widget.objectName() + "_Path" == widget.text()+ "_Path" :
                                Software["Software_Path"] = self.Software_Path_LineEdit.text()
                            
                            SoftwareList["Software"] =  Software
                
                for NewWidget in NewLauncher.findChildren(QtWidgets.QVBoxLayout):
                    if "NewLauncher_Layout" in NewWidget.objectName() :
                         for layout in NewWidget.findChildren(QtWidgets.QHBoxLayout):
                            print(layout.objectName())
                            if "Variable_horizontal_Layout" in layout.objectName():
                                Variable = {}  
                                for i in range(layout.count()):
                                    # 获取布局项
                                    Name = layout.itemAt(0)
                                    Value = layout.itemAt(1)
                                    Variable["Key"] = Name.widget().text()
                                    Variable["Value"] = Value.widget().text()

                                VariableList.append(Variable)
            SoftwareList["Variable"] =  VariableList 


            Project_info["Software"] = SoftwareList
            print(Project_info)



 

            #with open('H:\RareWolf_Toolkit\pipeline_tools\SoftwareStarter\Projecinfo/AHZ.json'.format(Project_info),
            #          'w') as fp:
            #    json.dump(Project_info, fp, indent=4, sort_keys=False)
#


if __name__ == '__main__':
    app = QApplication([]) if not QApplication.instance() else None
    MWin = mainWindow()
    for qt in QApplication.topLevelWidgets():
        if qt.windowTitle() == u'mainWindow':
            qt.close()
    MWin.show()
    app.exec_() if app else None
